using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Common
{
    public static partial class HtmlTranslate
    {
        internal static string FriendGetQuery(string Key, string Url)
        {
            Url = Url.Replace("&amp;", "&");
            if (Key == "Lang")
            {
                if (Regex.IsMatch(Url, @"\b-En\b"))
                {
                    return "En";
                }
                else return "Zh";
            }
            else
            {
                Match sect = Regex.Match(Url, @"\b-" + Key + @"\w*?\b");
                if (sect.Success)
                {
                    int value = sect.Value.TakeOutInt(-1);
                    if (value < 0)
                    {
                        return "True";
                    }
                    else return value.ToString();
                }
                else return "";
            }
        }

        internal static string FriendRemoveQuery(string Key, string Url)
        {
            Url = Url.Replace("&amp;", "&");
            if (Key == "Lang")
            {
                return Regex.Replace(Url, @"\b-En\b", "");
            }
            else
            {
                return Regex.Replace(Url, @"\b-" + Key + @"\w*?\b", "");
            }
        }

        /// <summary>
        /// 把真实的Url转换为友好的Url。会忽略掉 Key=false 的值，所以URL中 Key 默认都必须是 false。
        /// 逆方法为： ToRealUrl
        /// </summary>
        /// <param name="RealUrl"></param>
        /// <returns></returns>
        public static string ToFriendUrl(string RealUrl)
        {
            //需要对 －进行转义。
            //并且，Key和Value 的首字母不能是 - , ASPX 文件名不能包含 - ,参数里不能含有 .aspx

            if (RealUrl.HasValue() == false) return string.Empty;
            RealUrl = RealUrl.Replace("&amp;", "&");
            int index = RealUrl.ToLower().IndexOf(".aspx");
            if (index < 0) return RealUrl;

            string UrlFront = RealUrl.Substring(0, index);
            string UrlBehind = RealUrl.Substring(index);

            Dictionary<string, string> dict = SafeGetDictFromUrl(UrlBehind);

            string urlQuery = "";
            foreach (string item in dict.Keys)
            {
                string dkey = item.TrimStart('-').Replace("-", "--");
                string dval = dict[item].TrimStart('-').Replace("-", "--");

                if (string.Equals(dval, "false", StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }
                else if (string.Equals(dval, "true", StringComparison.CurrentCultureIgnoreCase))
                {
                    urlQuery += "-" + dkey;
                }
                else if (string.Equals(dkey, "Lang", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (dval == "En")
                    {
                        urlQuery += "-En";
                    }
                }
                else if (dval.TakeOutInt() != dval.GetInt(-1))
                {
                    urlQuery += "-" + dkey + "=" + dval;
                }
                else
                {
                    urlQuery += "-" + dkey + dval;
                }
            }
            return UrlFront + urlQuery + ".aspx";
        }

        /// <summary>
        /// 把伪Url转换为真实的Url。 逆方法为： ToFriendUrl
        /// 规则：真实的Url参数必须是以下三种情况：
        /// Key=true
        /// Key=Int
        /// Lang=En/Zh(目前，只解析了这两种。)
        /// </summary>
        /// <param name="FriendUrl"></param>
        /// <returns></returns>
        public static string ToRealUrl(string FriendUrl)
        {
            //需要对 －进行转义。
            //并且，Key和Value 的首字母不能是 -

            if (FriendUrl.HasValue() == false) return string.Empty;
            FriendUrl = FriendUrl.Replace("&amp;", "&");
            int aspxIndex = FriendUrl.ToLower().LastIndexOf(".aspx");

            if (aspxIndex < 0) return FriendUrl;

            int index = FriendUrl.Substring(0, aspxIndex).LastIndexOf("/");

            string UrlFront = FriendUrl.Substring(0, index);
            string UrlBehind = FriendUrl.Substring(index, aspxIndex - index);

            //可能含有 .aspx#
            string UrlAttend = FriendUrl.Substring(aspxIndex);


            string[] urlSects = UrlBehind.Replace("--", ValueProc.SplitCell.ToString()).Split('-');
            Dictionary<string, string> dict = new Dictionary<string, string>();

            for (int i = 1; i < urlSects.Length; i++)
            {
                string dval = urlSects[i].Replace(ValueProc.SplitCell.ToString(), "-");

                //找到开头第一个单词。
                Match _m = Regex.Match(dval, @"^[a-zA-Z]+", RegexOptions.Compiled);
                if (_m.Success)
                {
                    if (string.Equals(dval, "En", StringComparison.CurrentCultureIgnoreCase))
                    {
                        dict.Add("Lang", "En");
                    }
					else if ( string.Equals(dval,"Zh",StringComparison.CurrentCultureIgnoreCase ) ){
						dict.Add("Lang","Zh") ;
					}
                    else if (_m.Length == urlSects[i].Length)
                    {
                        dict.Add(dval, "True");
                    }
                    else
                    {
                        if (dval.Contains("="))
                        {
                            string[] _sect = dval.Split('=');
                            dict.Add(_sect[0], _sect[1]);
                        }
                        else
                        {
                            dict.Add(_m.Value, dval.Substring(_m.Length));
                        }
                    }
                }
            }

            foreach (var item in SafeGetDictFromUrl(UrlAttend))
            {
                if (dict.Keys.Contains(item.Key))
                {
                    dict[item.Key] = item.Value;
                }
                else
                {
                    dict.Add(item.Key, item.Value);
                }
            }

            if (dict.Count > 0)
            {
                return UrlFront + urlSects[0] + ".aspx?" + string.Join("&",
                    (from d in dict.Keys select d + "=" + dict[d]).ToArray()
                    );
            }
            else
            {
                return UrlFront + urlSects[0] + UrlAttend;
            }
        }
    }
}
